/**
 * @author
 * @createtime
 * @class ProjectExpensesForm
 * @extends Ext.Window
 * @description ProjectPayment表单
 */
ProjectExpensesForm = Ext.extend(Ext.Window, {
	//内嵌FormPanel
	formPanel : null,
	//构造函数
	constructor : function(_cfg) {
		Ext.applyIf(this, _cfg);
		//必须先初始化组件
		this.initUIComponents();
		ProjectExpensesForm.superclass.constructor.call(this, {
			id : 'ProjectExpensesFormWin',
			layout : 'fit',
			items : this.formPanel,
			modal : true,
			width : 800,
			height : 480,
			maximizable : true,
			title : '[费用报销]详细信息',
			buttonAlign : 'center',
			buttons : this.buttons
		});
	},//end of the constructor
	//初始化组件
	initUIComponents : function() {
		var thizId = this.id;
		var summary = new Ext.ux.grid.GridSummary();
		this.formPanel = new Ext.FormPanel({
			layout : 'form',
			trackResetOnLoad : true,
			bodyStyle : 'padding:10px 10px 10px 10px',
			border : false,
			url : __ctxPath + '/project/saveProjectExpenses.do',
			id : 'ProjectExpensesForm',
			defaults : {
				anchor : '98%,98%'
			},
			defaultType : 'textfield',
			items : [{
						name : 'projectExpenses.id',
						id : 'id',
						xtype : 'hidden',
						value : this.id == null ? '' : this.id
					}, {
						xtype : 'container',
						layout : 'column',
						height : 25,
						defaults : {
							xtype : 'label',
							style : {
								margin : '0px 0px 3px 0px'
							}
						},
						items : [{
									text : '项目名称：',
									width : 60
								}, {
									xtype : 'textfield',
									name : 'projectExpensesProName',
									id : 'projectExpensesProName',
									columnWidth : .4,
									allowBlank : false,
									emptyText : '请选择项目',
									listeners : {
										'focus' : function() {
											ProjectSelector.getView(function(proId, proName, proNo) {
												Ext.getCmp("projectExpenses.project.id").setValue(proId);
												Ext.getCmp("projectExpensesProName").setValue(proName);
											}, true).show();
										}
									}
								}, {
									xtype : "hidden",
									name : "projectExpenses.project.id",
									id : "projectExpenses.project.id"
								}, {
									text : '类型：',
									style : 'margin-left:10px;',
									width : 60
								}, {
									xtype : 'combo',
									hiddenName : 'projectExpenses.expensesType',
									id : 'expensesType',
									allowBlank : false,
									columnWidth : .3,
									triggerAction : 'all',
									mode : 'local',
									store : ['直接费', '间接费']
								}, {
									text : '填写日期：',
									style : 'margin-left:10px;',
									width : 60
								}, {
									xtype : 'datefield',
									name : 'projectExpenses.formDate',
									id : 'formDate',
									allowBlank : false,
									columnWidth : .3,
									format : 'Y-m-d',
									value : new Date()
								}]
					}, {
						xtype : 'container',
						layout : 'column',
						height : 25,
						defaults : {
							xtype : 'label',
							style : {
								margin : '0px 0px 3px 0px'
							}
						},
						items : [{
									text : '报销详情：'
								}, {
									style : 'color:red',
									id : 'projectExpensesErrorLabel',
									text : '(*必填)'
								}]
					}, {
						xtype : 'container',
						style : 'padding-left:0px;margin-bottom:10px',
						layout : 'column',
						items : [{
									name : 'resultGridData',
									xtype : 'hidden',
									id : 'projectExpenses.resultGridData'
								}, {
									name : 'dataList',
									xtype : 'hidden',
									id : 'projectExpenses.dataList'
								}, {
									xtype : 'grid',
									id : 'projectExpenses.resultGridDataGrid',
									height : 220,
									width : '98%',
									stripeRows : true,
									trackMouseOver : true,
									clicksToEdit : 1,
									plugins : [new Ext.ux.grid.RowEditor({
												saveText : '保存',
												cancelText : '取消',
												errorText : '请输入完整信息',
												errorSummary : false
											}), summary],
									store : new Ext.data.JsonStore({
										url : __ctxPath + '/project/listProjectExpensesInfo.do',
										root : 'result',
										totalProperty : 'totalCounts',
										remoteSort : true,
										fields : ['id', 'purpose', 'amount','billAmount', 'billAttachNum','fileAttachs'],
										listeners : {
											'update' : function(value) {
												var r = this.getRange();
												var resultArray = [];
												var jsonArr = [];
												var sum = 0;
												var rlen = r.length;
												for (var i = 0; i < rlen; i++) {
													resultArray.push([]);
													if (r[i].fields) {
														var fields = r[i].fields;
														var flen = fields.length;
														var obj = {
															id : null,
															purpose : '',
															amount : '',
															billAttachNum : ''
														}
														for (var z = 0; z < flen; z++) {
															var fieldValue = r[i].get(fields.keys[z]);
															if (Ext.isEmpty(fieldValue) || fieldValue == '请双击选择' || fieldValue == '请双击填写') {
																continue;
															}
															if (fields.keys[z] == 'id') {
																if (fieldValue != '') {
																	obj.id = fieldValue;
																}
															} else if (fields.keys[z] == 'purpose') {
																resultArray[i].push('用途:' + fieldValue);
																obj.purpose = fieldValue;
															} else if (fields.keys[z] == 'amount') {
																resultArray[i].push('金额（元）:' + fieldValue);
																obj.amount = fieldValue;
															} else if (fields.keys[z] == 'billAmount') {
																resultArray[i].push('发票金额（元）:' + fieldValue);
																obj.billAmount = fieldValue;
															} else if (fields.keys[z] == 'billAttachNum') {
																resultArray[i].push('附件数量（页）:' + fieldValue);
																obj.billAttachNum = fieldValue;
															} else if (fields.keys[z] == 'fileIds') {
																resultArray[i].push('附件ID:' + fieldValue);
																obj.fileIds = fieldValue;
															} else if (fields.keys[z] == 'fileContents') {
																resultArray[i].push('附件:' + fieldValue+ ';');
															}
														}
														jsonArr.push(obj);
													}
												}
												//删除空元素
												for (var i = 0; i < resultArray.length; i++) {
													if (resultArray[i].length == 0) {
														resultArray.splice(i, 1);
														i--;
													}
												}
												Ext.getCmp('projectExpenses.dataList').setValue(Ext.util.JSON.encode(jsonArr));
												Ext.getCmp('projectExpenses.resultGridData').setValue(resultArray);
											}
										}
									}),
									cm : new Ext.grid.ColumnModel({
										columns : [new Ext.grid.RowNumberer(), {
													dataIndex : 'id',
													width : 50,
													hidden : true
												}, {
													header : '用途',
													dataIndex : 'purpose',
													editor : new Ext.grid.GridEditor(new Ext.form.TextField({
														allowBlank : false,
														id : 'flow_purpose',
														maxLength : 64,
														listeners : {
															focus : function(field) {
																if (field.getValue() == '请双击填写') {
																	field.setValue('');
																}
															}
														}

													})),
													width : 200,
													summaryRenderer : function(v, params, data) {
														return '<font color="red">合计:</font>';
													}
												}, {
													header : '金额（元）',
													dataIndex : 'amount',
													width : 120,
													summaryType : 'sum',
													editor : new Ext.grid.GridEditor(new Ext.form.NumberField({
														id : 'flow_amount',
														allowBlank : false,
														maxLength : 9,
														regex : /^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/,
														regexText : '请输入正确格式的金额'
													}))
												}, {
												header : '发票金额（元）',
												dataIndex : 'billAmount',
												summaryType : 'sum',
												editor : new Ext.grid.GridEditor(new Ext.form.NumberField({
													allowBlank : false,
													maxLength : 9,
													regex : /^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/,
													regexText : '请输入正确格式的金额'
												}))
											}, {
												header : '附件数量（页）',
												dataIndex : 'billAttachNum',
												editor : new Ext.grid.GridEditor(new Ext.form.TextField({
													id : 'billAttachNum',
													maxLength : 64
												}))
//												summaryRenderer : function(v, params, data) {
//													var amount = data.gridData['amount'];
//													var amountBig = AmountInWords(amount)
//													Ext.getCmp('flow_projectExpenses.amount').setValue(amount);
//													Ext.getCmp('flow_projectExpenses.amountBig').setValue(amountBig);
//													return '<font color="red">大写:</font>' + amountBig;
//												}
											}, {
												header : '',
												dataIndex : 'fileIds',
												editor : new Ext.grid.GridEditor(new Ext.form.Hidden({
													id : 'fileIds'
												})),
												hidden:true
											}, {
												header : '附件',
												dataIndex : 'fileContents',
												width : 280,
												editor : new Ext.grid.GridEditor(new Ext.form.TextField({
													id : 'fileContents',
													readOnly:true,
													emptyText:'请上传附件',
													listeners:{
														focus:function(field){
															var dialog = App.createUploadDialog({
																	file_cat : 'flow/projectExpenses',
																	callback : function(data) {
																		if(!Ext.isEmpty(data)){
																			var attachFiles = Ext.getCmp("fileContents");
																			var fileIds = Ext.getCmp('fileIds');
																			fileIds.setValue('');
																			var str= "";
																			for (var i = 0; i < data.length; i++) {
																				if (fileIds.getValue() != '') {
																					fileIds.setValue(fileIds.getValue()+ ',');
																				}
																				fileIds.setValue(fileIds.getValue()+data[i].fileId);
																				str+='<span><a href="#" onclick="FileAttachDetail.show('+data[i].fileId+')">'+data[i].filename.replace(/\s+/g,"")+'</a>  |  </span>';
																			}
																			Ext.getCmp('fileContents').setValue(str);
																			Ext.getCmp('fileIds').setValue(fileIds.getValue());
																			Ext.getCmp('billAttachNum').setValue(data.length);
																		}
																	},
																	permitted_max_size :1024*1024*20
																});
															dialog.show(this);
														}
													}
												})),
												renderer:function(value,meta,record){
													var fileAttachs = record.data.fileAttachs;
													var str = "";
													Ext.each(fileAttachs,function(item,i){
														str+='<span><a href="#" onclick="FileAttachDetail.show('+item.fileId+')">'+item.fileName.replace(/\s+/g,"")+'</a>  |  </span>';
													});
													return str;
												}
											}],
										defaults : {
											sortable : false,
											menuDisabled : false,
											width : 100
										}
									}),
									tbar : new Ext.Toolbar({
										height : 30,
										items : [{
													iconCls : 'btn-add',
													text : '添加',
													xtype : 'button',
													handler : function() {
														var DataRecord = Ext.data.Record.create([{
																name : 'id'
															}, {
																name : 'purpose'
															}, {
																name : 'amount'
															}, {
																name : 'billAmount'
															}, {
																name : 'billAttachNum'
															}, {
																name : 'fileIds'
															}, {
																name : 'fileContents'
															}]);
														var store = Ext.getCmp('projectExpenses.resultGridDataGrid').store;
														var grid = Ext.getCmp('projectExpenses.resultGridDataGrid');
	
														var n1 = '请双击填写';
														var n2 = '';
														
														var newRowData = {
															purpose : n1,
															amount : n1,
															billAmount:n2,
															billAttachNum : n2,
															fileIds:n2,
															fileContents:n2
														};
														var newRecord = new DataRecord(newRowData);
														store.add([newRecord]);

														grid.getSelectionModel().on('selectionchange', function(sm) {
															Ext.getCmp('projectExpenses.removeBtn').setDisabled(sm.getCount() < 1);
														});
													}
												}, {
													iconCls : 'btn-del',
													text : '删除',
													id : 'projectExpenses.removeBtn',
													xtype : 'button',
													handler : function() {
														var store = Ext.getCmp('projectExpenses.resultGridDataGrid').store;
														var grid = Ext.getCmp('projectExpenses.resultGridDataGrid');
														var s = grid.getSelectionModel().getSelections();
														for (var i = 0, r; r = s[i]; i++) {
															store.remove(r);
														}
														store.fireEvent("update");//更新事件
													}
												}]
									})
								}]
					}, {
						xtype : 'textfield',
						hidden : true,
						validator : function() {
							var resultGridData = Ext.getCmp('projectExpenses.resultGridData').getValue();
							var errorLabel = Ext.getCmp("projectExpensesErrorLabel");
							if (Ext.isEmpty(thizId)) {
								if (Ext.isEmpty(resultGridData)) {//为空显示提示
									errorLabel.setText('请填写报销详情');
									return false;
								}
							}
							return true
						}
					}, {
					xtype : 'container',
					layout : 'column',
					height : 35,
					defaults : {
						xtype : 'label',
						style : {
							margin : '0px 0px 3px 0px'
						}
					},
					items : [{
								xtype : 'hidden',
								name : 'projectExpenses.isToLean',
								id : 'isToLean'
							},{
								text : '是否冲账备用金：',
								width : 120
							}, {
								xtype : 'checkbox',
								columnWidth : .4,
								name : 'sealChk',
								id:'sealChk',
								listeners : {
									check : function(field) {
										var val = field.getValue();
										if(val){
											Ext.getCmp('isToLean').setValue('是');
										}else{
											Ext.getCmp('isToLean').setValue('否');
										}
									}
								}
							},{
								text : '备用金/借款：',
								width : 90
							}, {
								xtype : 'numberfield',
								name : 'projectExpenses.leanAmount',
								id : 'leanAmount',
								columnWidth : .3,
								allowBlank : false,
								maxLength : 9,
								regex : /^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/,
								regexText : '请输入正确格式的金额'
							}, {
								text : '元'
							}]
				}, {
						xtype : 'container',
						layout : 'column',
						height : 60,
						defaults : {
							xtype : 'label',
							style : {
								margin : '0px 0px 3px 0px'
							}
						},
						items : [{
									text : '备注：',
									width : 60
								}, {
									xtype : 'textarea',
									name : 'projectExpenses.remark',
									id : 'remark',
									columnWidth : .98,
									height : 60
								}]
					}, {
						xtype : 'hidden',
						name : 'projectExpenses.amount',
						id : 'amount'
					}, {
						xtype : 'hidden',
						name : 'projectExpenses.amountBig',
						id : 'amountBig'
					}]
		});
		//加载表单对应的数据	
		this.initData();
		//初始化功能按钮
		this.buttons = [
//				{
//					text : '保存',
//					iconCls : 'btn-save',
//					handler : this.save.createCallback(this.formPanel, this)
//				}, {
//					text : '重置',
//					iconCls : 'btn-reset',
//					handler : this.reset.createCallback(this.formPanel)
//				},
				{
					text : '关闭',
					iconCls : 'btn-cancel',
					handler : this.cancel.createCallback(this)
				}];
	},//end of the initcomponents
	/**
	 * 初始化数据
	 * 
	 * @param {}
	 *            formPanel
	 */
	initData : function() {
		//加载表单对应的数据	
		if (this.id != null && this.id != 'undefined') {
			Ext.getCmp('projectExpenses.resultGridDataGrid').getStore().load({params:{
					'Q_projectExpenses.id_L_EQ':this.id,
					start:0,
					limit:9999
			}});
			this.formPanel.getForm().load({
				deferredRender : false,
				url : __ctxPath + '/project/getProjectExpenses.do?id=' + this.id,
				waitMsg : '正在载入数据...',
				success : function(form, action) {
					var jsonData = Ext.util.JSON.decode(action.response.responseText);
					var res = jsonData.data;
					if (!Ext.isEmpty(res.project)) {
						Ext.getCmp("projectExpensesProName").setValue(res.project.proName);
						Ext.getCmp("projectExpensesProName").originalValue = res.project.proName;
						Ext.getCmp("projectExpenses.project.id").setValue(res.project.id);
						Ext.getCmp("projectExpenses.project.id").originalValue = res.project.id;
					}
					if(res.isToLean=='是'){
						Ext.getCmp('sealChk').setValue(true);
					}
					//Ext.getCmp("").originalValue=
				},
				failure : function(form, action) {
				}
			});
		}
	},
	/**
	 * 重置
	 * 
	 * @param {}
	 *            formPanel
	 */
	reset : function(formPanel) {
		formPanel.getForm().reset();
	},
	/**
	 * 取消
	 * 
	 * @param {}
	 *            window
	 */
	cancel : function(window) {
		window.close();
	},
	/**
	 * 保存记录
	 */
	save : function(formPanel, window) {
		if (formPanel.getForm().isValid()) {
			formPanel.getForm().submit({
				method : 'POST',
				waitMsg : '正在提交数据...',
				success : function(fp, action) {
					Ext.ux.Toast.msg('操作信息', '成功保存信息！');
					var gridPanel = Ext.getCmp('ProjectExpensesGrid');
					if (gridPanel != null) {
						gridPanel.getStore().reload();
					}
					window.close();
				},
				failure : function(fp, action) {
					Ext.MessageBox.show({
						title : '操作信息',
						msg : '信息保存出错，请联系管理员！',
						buttons : Ext.MessageBox.OK,
						icon : Ext.MessageBox.ERROR
					});
//					window.close();
				}
			});
		}
	}//end of save

});